<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Cache;

class HomepageRecommendModule extends Model
{
    protected $fillable = ['title','created_at','updated_at','deleted','deleted_at','sort'];

    public function books()
    {
        return $this->belongsToMany(Book::class, 'book_homepage_recommend_module_relations','book_homepage_recommend_module_id','book_id');
    }

    public function getHomepageRecommendModules()
    {
        return Cache::remember('book-shop:homepage-recommend-modules:modules', 24*60, function(){
            return $this->homepageRecommendModulesList();
        });
    }

    private function homepageRecommendModulesList()
    {
        $modules[] = ['id' => -1,'title' => '猜你喜欢'];

        $modules_list = $this->newQuery()->where('deleted',0)->orderBy('sort','asc')->get();
        if(!empty($modules_list))
        {
            foreach ($modules_list as $v)
            {
                $modules[] = [
                    'id'    => $v->id,
                    'title' => $v->title,
                ];
            }
        }

        return $modules;
    }
}
